<?php

namespace app\xs_wxpay\controller\web;

use xsframe\base\AdminBaseController;
use xsframe\facade\service\DbServiceFacade;
use xsframe\util\ArrayUtil;

class Sets extends AdminBaseController
{
    public function account()
    {
        $uniacid = $this->uniacid;
        $accountSettings = $this->settingsController->getAccountSettings($uniacid, 'settings');

        if ($this->request->isPost()) {
            $settingsData = $this->params['data'] ?? [];

            if (!empty($_FILES)) {
                if ($_FILES['wxpay_cert_file']['name']) {
                    $settingsData['wxpay']['cert_file'] = $this->upload_cert('wxpay_cert_file');
                }

                if ($_FILES['wxpay_key_file']['name']) {
                    $settingsData['wxpay']['key_file'] = $this->upload_cert('wxpay_key_file');
                }
            }

            $settingsData = ArrayUtil::customMergeArrays($accountSettings, $settingsData);
            $data['settings'] = serialize($settingsData);

            DbServiceFacade::name("sys_account")->updateInfo($data, ['uniacid' => $uniacid]);

            $this->settingsController->reloadAccountSettings($uniacid);
            $this->success();
        }

        $result = [
            'accountSettings' => $accountSettings,
        ];
        return $this->template('account', $result);
    }

    // 解析证书
    private function upload_cert($fileinput)
    {
        $filename = $_FILES[$fileinput]['name'];
        $tmp_name = $_FILES[$fileinput]['tmp_name'];
        if (!empty($filename) && !empty($tmp_name)) {
            $ext = strtolower(substr($filename, strrpos($filename, '.')));

            if ($ext != '.pem') {
                $errinput = '';

                if ($fileinput == 'cert_file') {
                    $errinput = 'CERT文件格式错误';
                } else if ($fileinput == 'key_file') {
                    $errinput = 'KEY文件格式错误';
                }

                show_json(0, $errinput . ',请重新上传!');
            }

            return file_get_contents($tmp_name);
        }

        return '';
    }
}
